<?php
// app/src/App/User/UserProvider.php
namespace Secret\Users;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Util\Debug;

class UserProvider implements UserProviderInterface {

	private $conn;

	public function __construct(EntityManager $conn) {
		$this->conn = $conn;
	}

	public function loadUserByUsername($username) {
		$repo = $this->conn->getRepository('Secret\Entities\Content');
		$result = $repo->data('User', 'entity.login = :v1', array('v1' => $username));
		
		if (count($result['_data']) == 0) {
			throw new UsernameNotFoundException(sprintf('Login "%s" does not exist.', $username));
		}
		$user = new User($result['_data'][0]['login'], $result['_data'][0]['password'], array('ROLE_ADMIN'), true, true, true, true);
		$user->name = $result['_data'][0]['name'];
		$user->admin = $result['_data'][0]['admin'];
		return $user;
	}

	public function refreshUser(UserInterface $user) {
		if (! $user instanceof User) {
			throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
		}
		return $this->loadUserByUsername($user->getUsername());
	}

	public function supportsClass($class) {
		return $class === 'Secret\Entities\User';
	}
}